/***********************************************************************
 * Module:  DefaultFileResource.java
 * Author:  wuxinyang
 * Purpose: Defines the Class DefaultFileResource
 ***********************************************************************/

package com.witframework.plugin.lucene.resource.impl;

import java.io.File;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;

import com.witframework.plugin.lucene.index.ResourceProcessor;


/**
 * 文件系统索引实现类，文件资源的处理由知识库系统完成，搜索系统暂不实现
 *
 * @pdOid 7301b5cd-18a0-464c-a43a-ce7efee977be
 */
public class DefaultFileSystemResource extends AbstractResource {
	private static final Log log = LogFactory	.getLog(DefaultFileSystemResource.class);

	protected String[] baseDirs;
	protected String[] excludedFiles;
	private int fileCount;

	public int extractDocuments(ResourceProcessor holder){
		if (baseDirs == null || baseDirs.length == 0) {
			return 0;
		}
		fileCount = 0;
		for (String base : baseDirs) {
			File file = new File(base);
			if (file.exists()) {
				visitFileRecursively(file,holder);
			} else {
				log.warn("File " + file + " does not exist; ignored");
			}
		}
		return fileCount;
	}

	protected void visitFileRecursively(File file,ResourceProcessor holder) {
		if (file.isFile()) {
			if (!isExcluded(file)) {
				Document doc = buildDocument(file);
				if (doc != null) {
					Field field = new Field("fileName", file.getName(),
							Store.YES, Index.TOKENIZED);
					doc.add(field);
					field = new Field("filePath", file.getAbsolutePath(),
							Store.YES, Index.NO);
					doc.add(field);
					field = new Field("size", file.length() / 1024 + "KB", Store.YES, Index.NO);
					doc.add(field);
					doc.add(new Field("rType", "f",Field.Store.YES,Field.Index.NO));
					fileCount++;
					holder.addDocument(doc);
				}
			}
		} else if (file.isDirectory()) {
			File[] ls = file.listFiles();
			for (File f : ls) {
				visitFileRecursively(f,holder);
			}
		} else {
			log.warn("Unsupported file type: " + file.getPath());
		}
	}

	protected Document buildDocument(File file) {
		return new Document();
	}

	protected boolean isExcluded(File file) {
		return false;
	}
	public void setBaseDirs(String[] baseDirs) {
		this.baseDirs = baseDirs;
	}

	public void setBaseDir(String baseDir) {
		this.baseDirs = new String[] { baseDir };
	}

	public void setExcludedFiles(String[] excluded) {
		this.excludedFiles = excluded;
	}

	public void setExcludedFile(String excluded) {
		this.excludedFiles = new String[] { excluded };
	}

}